import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.stream.Stream;

public class Soup {
    private static final String TEXT_NAME = "scope.text";

    public static void soupAndStore(String html) {
        HashMap<String, Integer> map = new HashMap<>(69);
        Document doc = Jsoup.parse(html);
        Elements rows = doc.getElementsByClass("homework-item");
        rows.forEach(row -> {
            Elements member = row.select(".member-message");
            String name = member.get(0).text();
            String number = member.get(1).text();
            String key = number + ", " + name +", ";
            Integer scope = Integer.parseInt(row.select(".appraised-type").get(1).child(1).text().split(" ")[0]);
            if(map.containsKey(key)){
                map.replace(key, map.get(key) + scope);
            } else {
                map.put(key, scope);
            }
        });
        Stream<Integer> valueSteam = map.values().stream();
        Integer max = valueSteam.max(Integer::compareTo).orElse(0);
        Integer min = valueSteam.min(Integer::compareTo).orElse(0);
        double average = valueSteam.mapToLong(e -> e.longValue()).average().orElse(0);
        StringBuffer buffer = new StringBuffer();
        buffer
                .append("最高经验值： ")
                .append(max).append(", 最低经验值： ")
                .append(min).append(", 平均经验值： ")
                .append(average)
                .append("\n");
        map.forEach((key, value) -> {
            buffer.append(key).append(value).append("\n");
        });
        try {
            FileWriter writer = new FileWriter(TEXT_NAME);
            writer.write(buffer.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
